/**
 * Title: BaseActivity.java
 * Description:
 * Copyright: Copyright (c) 2008
 * Company:深圳彩讯科技有限公司
 * Author 罗旭东 (hi@luoxudong.com)
 * Date 2013-8-06 上午10:10:44
 * Version 1.0
 */
package com.luoxudong.phonenumber.ui.activities;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Stack;

import android.app.Activity;
import android.content.Context;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.Window;
import android.view.WindowManager;

import com.luoxudong.phonenumber.R;
import com.luoxudong.phonenumber.service.utils.EvtLog;
import com.luoxudong.phonenumber.ui.widgets.CommonProgressDialog;

/** 
 * ClassName: BaseActivity
 * Description:Activity的基类
 * Create by 罗旭东
 * Date 2013-8-06 上午10:10:44
 */
public abstract class BaseActivity extends Activity{
	/**
	 * 初始化消息,数值取大一些，避免跟子类中的消息冲突
	 */
	private static final int MSG_INIT = Integer.MAX_VALUE - 1;
	
	/**
	 * 网络异常
	 */
	protected static final int MSG_NETWORK_INVALID = Integer.MAX_VALUE - 2;
	
	/**
	 * sd卡不可用
	 */
	protected static final int MSG_SDCARD_UN_READY = Integer.MAX_VALUE - 3;
	
	/**
	 * 刷新UI
	 */
	protected static final int MSG_REFRESH_UI = Integer.MAX_VALUE - 4;
	
	/**
	 * 错误信息
	 */
	protected static final int MSG_EXCEPTION = Integer.MAX_VALUE - 5;
	
	/**
	 * 保存活动activity的栈
	 */
	private static Stack<BaseActivity> activities = null;
	
	/**
	 * 需要刷新的activity列表
	 */
	private static List<BaseActivity> refreshActivities = null;
	
	/**
	 * 等待框
	 */
	private CommonProgressDialog progressDialog = null;
	
	/**
	 * 是否隐藏等待框
	 */
	private boolean isHiddenProgressDialog = true;
	
	/**
	 * 屏幕宽度
	 */
	protected int screenWidth = 0;
	
	/**
	 * 屏幕高度
	 */
	protected int screenHeight = 0;
	
	/**
	 * 密度
	 */
	public static float scale = 0f;
	
	/**
	 * 布局文件ID
	 * @return 布局文件ID
	 */
	protected abstract int getContentViewLayoutResId();
	
	/**
	 * 初始化界面 （加载控件View对象）
	 *
	 */
	protected abstract void onCreateFindView(Bundle savedInstanceState);

	/**
	 * 加载操作事件（View控件的点击事件响应等，控件的监听方法）
	 *
	 */
	protected abstract void onCreateAddListener(Bundle savedInstanceState);

	/**
	 * 放入初始化的数据(onCreate主线程加载处理，用于不耗时操作或起线程操作)
	 *
	 */
	protected abstract void onCreateInitData(Bundle savedInstanceState);

	/**
	 * 线程加载数据（用于后台处理耗时操作，主要用于数据库读取或发送请求操作，该方法中不能有UI操作，有UI操作会有不可预料的异常）
	 */
	protected abstract void onCreateTaskLoadData();

	/**
	 * 线程加载View（后台数据加载完后，用于界面View控件刷新操作，不能有后台耗时处理，会堵塞主线程）
	 */
	protected abstract void onCreateTaskAddView();
	
	
	/**
	 * 刷新UI
	 */
	protected abstract void refreshUI(Object obj);
	
	private Handler baseHandler = new Handler()
	{
		@Override
		public void handleMessage(Message msg)
		{
			switch (msg.what)
			{
				case MSG_INIT://activity初始化
					InitTask initTask = new InitTask();
					initTask.execute();
					break;
				case MSG_NETWORK_INVALID://网络异常
					break;
				case MSG_SDCARD_UN_READY://SD卡不存在
					break;
				case MSG_REFRESH_UI://刷新UI
					refreshUI(msg.obj);
					break;
				case MSG_EXCEPTION://错误信息
					if (msg.obj != null && msg.obj instanceof Object[])
					{
						Object[] errorInfo = (Object[])msg.obj;
						if (errorInfo.length >= 2 && errorInfo[0] instanceof Integer && errorInfo[2] instanceof String)
						{
							handleErrorMsg((Integer)errorInfo[0], (String)errorInfo[1]);
						}
						
					}
					break;
				default:
					super.handleMessage(msg);
					break;
			}
			
			BaseActivity.this.handleMessage(msg);
		}
	};
	
	@Override
	public void onCreate(Bundle savedInstanceState) {
		requestWindowFeature(Window.FEATURE_NO_TITLE);//去掉标题栏
		super.onCreate(savedInstanceState);
		if (getContentViewLayoutResId() != 0)
		{
			setContentView(getContentViewLayoutResId());
		}
		
		WindowManager wm = (WindowManager) this.getSystemService(Context.WINDOW_SERVICE);

		screenWidth = wm.getDefaultDisplay().getWidth();//屏幕宽度

		screenHeight = wm.getDefaultDisplay().getHeight();//屏幕高度
		
		scale = getResources().getDisplayMetrics().density;
		
		onCreateFindView(savedInstanceState);
		
		onCreateAddListener(savedInstanceState);
		
		showProgressDialog(null, getResources().getString(R.string.msg_loading));
		
		onCreateInitData(savedInstanceState);

		sendMessage(obtainMessage(MSG_INIT, null));
		
		addActivity(this);
	}
	
	@Override
	protected void onDestroy() {
		EvtLog.d("BaseActivity", "正在关闭activity" + this);
		removeActivity(this);
		System.gc();
		
		super.onDestroy();
	}
	
	@Override
	protected void onPause() {
		super.onPause();
	}
	
	@Override
	protected void onResume() {
		super.onResume();
		refreshActivityUI(this);//刷新界面
	}
	
	/**
	 * 添加需要刷新的activity
	 * @param activity
	 */
	public static void addRefreshActivity(BaseActivity activity)
	{
		if (refreshActivities == null)
		{
			refreshActivities = new ArrayList<BaseActivity>();
		}
		
		synchronized (refreshActivities) {
			if (!refreshActivities.contains(activity))
			{
				refreshActivities.add(activity);
			}
		}
	}
	
	/**
	 * 删除刷新activity
	 * @param activity
	 */
	public static void removeRefreshActivity(BaseActivity activity)
	{
		synchronized (refreshActivities) {
			if (refreshActivities != null && refreshActivities.contains(activity))
			{
				refreshActivities.remove(activity);
			}
		}
	}
	
	/**
	 * 刷新UI
	 * @param activity
	 */
	private void refreshActivityUI(BaseActivity activity)
	{
		if (refreshActivities != null && refreshActivities.contains(activity))
		{
			sendMessage(obtainMessage(MSG_REFRESH_UI, null));
			removeRefreshActivity(activity);
		}
	}
	
	/**
	 * 设置等待框状态
	 * @param isHide
	 */
	protected void setHideProgressDialog(boolean isHide)
	{
		this.isHiddenProgressDialog = isHide;
	}
	
	private class InitTask extends AsyncTask<String, Integer, String>
	{
		@Override
		protected void onPreExecute()
		{
			//super.onPreExecute();
		}
		
		@Override
		protected String doInBackground(String... params)
		{
			onCreateTaskLoadData();
			return null;
		}
		
		@Override
		protected void onPostExecute(String result)
		{
			onCreateTaskAddView();
			hiddenProgressDialog();
		}
		
	}
	
	/**
	 * 显示等待框
	 * @param title
	 * @param msg
	 */
	protected void showProgressDialog(String title, String msg)
	{
		if (!isHiddenProgressDialog)
		{
			progressDialog = new CommonProgressDialog(this);
			
			if (msg == null)
			{
				msg = getResources().getString(R.string.msg_loading);
			}
			progressDialog.setMessage(msg);
			progressDialog.show();
		}
	}
	
	/**
	 * 隐藏等待框
	 */
	protected void hiddenProgressDialog()
	{
		if (!isHiddenProgressDialog && progressDialog != null)
		{
			progressDialog.dismiss();
		}
	}
	
	/**
	 * dip转px
	 * @param dip
	 * @return
	 */
	public static int dip2Px(int dip)
	{
		return (int)(dip * scale + 0.5f);
	}
	
	private void addActivity(BaseActivity baseActivity)
	{
		if (activities == null)
		{
			activities = new Stack<BaseActivity>();
		}
		
		activities.push(this);
	}
	
	private void removeActivity(BaseActivity baseActivity)
	{
		if (activities != null && activities.contains(baseActivity))
		{
			activities.remove(baseActivity);
		}
	}
	
	public static void releaseAllActivities() {
		if (activities != null && !activities.empty()) {
			Iterator<BaseActivity> iterator = activities.iterator();
			while (iterator.hasNext()) {
				BaseActivity baseActivity = iterator.next();
				if (baseActivity == null) {
					continue;
				}

				baseActivity.finish();
			}
			activities.clear();
		}
	}
	
	/**
	 * 
	 * @description:获取栈顶的activity对象
	 * @return
	 * @return BaseActivity
	 * @throws
	 */
	public static BaseActivity getTopActivity() {
		if (activities != null && !activities.empty())
		{
			return activities.peek();
		}
		
		return null;
	}
	
	protected void handleErrorMsg(int errorCode, String errorMsg){}
	
	/**
	 * 
	 * @description:消息发送给子类
	 * @param msg 消息
	 * @return void
	 * @throws
	 */
	protected void handleMessage(Message msg) {
	}
	
	protected Message obtainMessage(int what, Object obj) {
        Message msg = null;
        if(baseHandler != null){
            msg = baseHandler.obtainMessage(what, obj);
        }else{
            msg = Message.obtain();
            msg.what = what;
            msg.obj = obj;
        }
        return msg;
    }
	
	protected void sendMessage(Message msg) {
        if(baseHandler != null){
        	baseHandler.sendMessage(msg);
        } else {
            handleMessage(msg);
        }
    }

	protected void sendMessage(Message msg, long delayMillis) {
        if(baseHandler != null){
        	baseHandler.sendMessageDelayed(msg, delayMillis);
        } else {
            handleMessage(msg);
        }
    }
	
}
